package my.webservices.model;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

public class AuditTrailInterceptor extends EmptyInterceptor {

	private static final long serialVersionUID = 1L;

	@Override
	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		setValue(currentState, propertyNames, "UPDATED_BY", "SYSTEM");
		setValue(currentState, propertyNames, "UPDATE_DATE", new Date());
		return true;
	}

	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		setValue(state, propertyNames, "CREATED_BY", "SYSTEM");
		setValue(state, propertyNames, "CREATE_DATE", new Date());
		return true;
	}

	private void setValue(Object[] currentState, String[] propertyNames,
			String propertyToSet, Object value) {
		int index = Arrays.asList(propertyNames).indexOf(propertyToSet);
		if (index >= 0) {
			currentState[index] = value;
		}
	}
}
